<?php

namespace App\Http\Controllers;

use App\Models\Message;
use App\Models\MessageTemplate;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;
use App\Http\Repositories\SignatureHelper;

class SmsController extends Controller
{

    /**
     * 发送短信
     *
     * @return array()
     */
    public function index(Request $request)
    {
        $mobile = $request->post('mobile');
        $templateCode = $request->post('type');

        $send = Message::where('mobile' , $mobile)->where('message_template_id', $templateCode)->where('is_use', '0')->first();

        //开启事务
        DB::beginTransaction();
        $code = '';

        if(!empty($send) && strtotime($send->overdue_at) >= time()) {
            $send_time = strtotime($send->send_at) + 60;
            //避免用户太频繁发送短信
            if($send_time >= time()) {
                return ['code' => 0, 'message' => '用户发送短信较频繁，请稍等60s后再发送', 'data' => ''];
            }
            $res = Message::where('id' , $send->id)->update(['overdue_at' => date('Y-m-d H:i:s', time()+300)]);

            $code = $send->code;
        }else{
            $content = MessageTemplate::where('template_code', $templateCode)->value('content');

            if(empty($content)) {
                return ['code' => 0, 'message' => '用户非法操作', 'data' => ''];
            }
            $code = randFloat();
            $message = str_replace('{code}', $code, $content);

            $inset = [
                'mobile' => $mobile,
                'message_template_id' => $templateCode,
                'code' => $code,
                'message' => $message,
                'send_at' =>date('Y-m-d H:i:s', time()),
                'overdue_at' =>date('Y-m-d H:i:s', time()+300),
                'is_use' => '0',
                'type' => '1'
            ];
            $res = Message::create($inset);
        }
        if(!$res) {
            DB::rollback();
            return ['code' => 0, 'message' => '用户发送短信失败', 'data' => ''];
        }

        if(Config::get('system.environment') == 'production') {
            //调取短信通道
            $templateParam = array(
                'code' => $code,
            );

            $aliYun = $this->aliYun($mobile, $templateCode, $templateParam);
            if ($aliYun->Code != 'OK') {
                DB::rollBack();
                return ['code' => 0, 'message' => $aliYun->Message, 'data' => ''];
            }
        }


        //提交数据
        DB::commit();
        return ['code' => 1, 'message' => '发送成功', 'data' => ''];
    }

    /**
     * 发送短信
     *
     * @return bool|\stdClass
     */
    public function aliYun($mobile, $templateCode, $templateParam) {
        $params = array ();

        $aliYun = Config::get("sms.aliYun");

        // *** 需用户填写部分 ***
        // 是否启用https
        $security = false;

        // 获取用户AK信息
        $accessKeyId = $aliYun['accessKeyId'];
        $accessKeySecret = $aliYun['accessKeySecret'];

        // 短信发送手机号
        $params["PhoneNumbers"] = $mobile;

        // 短信签名
        $params["SignName"] = $aliYun['SignName'];

        // 模板短信code
        $params["TemplateCode"] = $templateCode;

        if(!empty($templateParam)) {
            // 模板变量
            $params['TemplateParam'] = $templateParam;
        }

        // *** 需用户填写部分结束, 以下代码若无必要无需更改 ***
        if(!empty($params["TemplateParam"]) && is_array($params["TemplateParam"])) {
            $params["TemplateParam"] = json_encode($params["TemplateParam"], JSON_UNESCAPED_UNICODE);
        }

        //此处可能会抛出异常，注意catch
        $sign = new SignatureHelper();
        $content = $sign->request(
            $accessKeyId,
            $accessKeySecret,
            "dysmsapi.aliyuncs.com",
            array_merge($params, array(
                "RegionId" => "cn-hangzhou",
                "Action" => "SendSms",
                "Version" => "2017-05-25",
            )),
            $security
        );

        return $content;
    }
}
